struct Solution;

impl Solution {
    pub fn character_replacement(s: String, k: i32) -> i32 {
        if s.is_empty() {
            return 0;
        }

        let bytes = s.into_bytes();
        let k = k as usize;
        let mut low = 0;
        let mut chars_num = [0; 26];

        for (index, char) in bytes.iter().enumerate() {
            let char_index = (*char - b'A') as usize;
            chars_num[char_index] += 1;
            if index >= k {
                let max = *chars_num.iter().max().unwrap();
                let rest = index - low + 1 - max;
                if rest > k {
                    chars_num[(bytes[low] - b'A') as usize] -= 1;
                    low += 1;
                }
            }
        }

        (bytes.len() - low) as i32
    }
}

#[cfg(test)]
mod test {
    use crate::Solution;

    #[test]
    fn test_01() {
        let s = String::from("ABAB");
        let k = 2;
        assert_eq!(Solution::character_replacement(s, k), 4);
    }

    #[test]
    fn test_02() {
        let s = String::from("AABABBA");
        let k = 1;
        assert_eq!(Solution::character_replacement(s, k), 4);
    }


    #[test]
    fn test_03() {
        let s = String::from("A");
        let k = 2;
        assert_eq!(Solution::character_replacement(s, k), 1);
    }

    #[test]
    fn test_04() {
        let s = String::from("AAAAAA");
        let k = 0;
        assert_eq!(Solution::character_replacement(s, k), 6);
    }


    #[test]
    fn test_05() {
        let s = String::from("ABAA");
        let k = 0;
        assert_eq!(Solution::character_replacement(s, k), 2);
    }

    #[test]
    fn test_06() {
        let s = String::from("");
        let k = 0;
        assert_eq!(Solution::character_replacement(s, k), 0);
    }
}

fn main() {
    let s = String::from("");
    let k = 0;
    assert_eq!(Solution::character_replacement(s, k), 0);
}
